package com.waves.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

/**
 * 服务端
 */
public class HelloServer {
    public static void main(String[] args) {
        // 1. 创建服务器启动类
        new ServerBootstrap()
                // 2. 添加处理器组，包含线程池和Selector，用于实现并发和监听就绪通道
                // BossEventLoop负责处理连接的组 WorkerEventLoop负责处理读写的组
                .group(new NioEventLoopGroup(),new NioEventLoopGroup())
                // 3. 选择通道的实现，可以是NIO或BIO
                .channel(NioServerSocketChannel.class)
                // 4. 用来指定 worker处理器组 需要处理的任务
                .childHandler(
                        // 5.初始化通道
                        new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            // 具体初始化
                            protected void initChannel(NioSocketChannel ch) {
                                // pipeline 业务工作流
                                ch.pipeline().addLast(new StringDecoder());
                                ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) {
                                        System.out.println(msg);
                                    }
                                });
                            }
                        }
                )
                .bind(8080);
    }
}
